import {
	getCityInfo
} from "@/api/tianqi.js"
const {
	weatherKey
} = require('@/config/constant.js');

/**
 *  @description 获取定位信息
 *  @returns {}
 */
export function getLocation() {
	return new Promise((resolve, reject) => {
		uni.authorize({
			scope: "scope.userLocation",
			success: async (res) => {
				const data = await getLocationInfo()
				resolve(data)
			},
			fail() {
				reject()
				openConfirm();
			}
		})
	})
}

/**
 * 再次获取授权
 * 当用户第一次拒绝后再次请求授权
 */
function openConfirm() {
	uni.showModal({
		title: '请求授权当前位置',
		content: '需要获取您的地理位置，请确认授权',
		success: (res) => {
			if (res.confirm) {
				uni.openSetting(); // 打开地图权限设置
			} else if (res.cancel) {
				uni.showToast({
					title: '你拒绝了授权，无法获得周边信息',
					icon: 'none',
					duration: 1000
				})
			}
		}
	});
}

/**
 *  @description 获取定位信息
 *  @returns {string}
 */
function getLocationInfo() {
	return new Promise((resolve, reject) => {
		uni.getLocation({
			type: 'wgs84',
			geocode: true,
			success: async (res) => {
				const {
					longitude,
					latitude
				} = res;
				const data= await getCityInfo({
					key: weatherKey,
					location: longitude + ',' + latitude
				})
				resolve(data)

			},
			fail: err => {
				reject('获取定位失败')
			}
		});
	})
}
